import { Layout, Button, Space, Modal, message, Table } from 'myselfantd';
import React, { useEffect, useState } from 'react';
import type { ColumnsType, TableProps } from 'antd/es/table';
import DynamicContent from './DynamicContent';
import styles from './index.module.scss';
// import { getList } from '../api';
interface DataType {
  code: number;
  work: string;
  operateArea: number;
  operateDistance: number;
  taskEndTime: string;
  taskStatus: number;
  evaluationState: number;
  option: [];
}
interface Props {
  viewmode?: 'view' | 'add' | 'edit';
  data?: any;
  onChange?: Function;
}
const App: React.FC<Props> = (props) => {
  const { viewmode, data, onChange } = props;
  const [units, setUnits] = useState<any>([]);
  useEffect(() => {
    // getList({}).then(({ result }: any) => {
    //   setUnits(result);
    // });
  }, []);
  const [tableData, setTableData] = useState({
    data: [] as ColumnsType<DataType>,
    page: { total: 0, pageSize: 10, current: 1 },
  });
  const [reload, setReload] = useState(0);
  const [editData, setEditData] = useState({});
  useEffect(() => {
    if (data) {
      setTableData({
        data: data as ColumnsType<DataType>,
        page: { total: data.length, pageSize: 20, current: 1 },
      });
      setReload(reload + 1);
    }
  }, [data]);
  const [curState, setCurState] = useState([false, 'view'] as [boolean, string]);
  return (
    <div style={{ marginBottom: '20px' }}>
      <Layout.PageTemplate
        reload={reload}
        padding={0}
        height={0}
        title="动态属性"
        tabBarExtraContent={
          viewmode === 'add' && (
            <Button.Image
              size="large"
              style={{ position: 'absolute', right: '10px', top: '10px' }}
              type="primary"
              onClick={() => setCurState([true, 'add'])}
              icon={'add'}
            >
              添加动态属性
            </Button.Image>
          )
        }
        search={false}
        table={{
          template: [
            {
              title: '序号',
              width: 150,
              fixed: 'left',
              align: 'left',
              render: (text, record, index) => {
                return index + 1;
              },
            },
            {
              title: '属性名称',
              width: 150,
              fixed: 'left',
              align: 'left',
              dataIndex: 'name',
            },
            {
              title: '标识符',
              width: 150,
              textWrap: 'word-break',
              align: 'left',
              dataIndex: 'code',
            },
            {
              title: '数据类型',
              width: 150,
              textWrap: 'word-break',
              align: 'left',
              dataIndex: 'type',
              render: (_) => {
                enum TYPE {
                  数字类型 = 1,
                  字符串类型 = 2,
                  布尔类型 = 3,
                  枚举类型 = 4,
                }
                return TYPE[_];
              },
            },
            {
              title: '数据定义',
              width: 220,
              textWrap: 'word-break',
              ellipsis: true,
              align: 'left',
              dataIndex: 'valueJson',
              render: (_, record: any) => {
                let targetData = JSON.parse(_);
                let dom: any = '';
                switch (record.type) {
                  case 1:
                    dom = (
                      <span>
                        <p>
                          <span>定义取值范围：</span>
                          {targetData.min} ~ {targetData.max}
                        </p>
                        <p>
                          <span>步长：</span>
                          {targetData.walkLength}
                        </p>
                        <p>
                          <span>单位：</span>
                          {units.find((item: any) => item.id === String(targetData.unitId))?.name}
                        </p>
                      </span>
                    );
                    break;
                  case 2:
                    dom = (
                      <span>
                        <span>数据长度：</span>
                        {targetData.stringResult}
                      </span>
                    );
                    break;
                  case 3:
                    dom = (
                      <span>
                        <span>布尔值：</span>
                        <Table.Edit
                          deleteButton={false}
                          value={targetData.booleanEnums.map((item: any, index: any) => ({
                            sortkey: index,
                            ...item,
                          }))}
                          pagination={false}
                          columns={[
                            {
                              title: '参数值',
                              dataIndex: 'enumKey',
                              showSorterTooltip: false,
                              width: 180,
                              onCell: (record: any) => {
                                return {
                                  filed: 'enumKey',
                                  record,
                                };
                              },
                            },
                            {
                              title: '参数描述',
                              dataIndex: 'enumDesc',
                              showSorterTooltip: false,
                              onCell: (record: any) => ({
                                filed: 'enumDesc',
                                record,
                              }),
                            },
                          ]}
                        />
                      </span>
                    );
                    break;
                  case 4:
                    dom = (
                      <span>
                        <span>枚举值：</span>
                        <Table.Edit
                          deleteButton={false}
                          value={targetData.enums.map((item: any, index: any) => ({
                            sortkey: index,
                            ...item,
                          }))}
                          pagination={false}
                          columns={[
                            {
                              title: '参数值',
                              dataIndex: 'enumKey',
                              showSorterTooltip: false,
                              width: 180,
                              onCell: (record: any) => {
                                return {
                                  filed: 'enumKey',
                                  record,
                                };
                              },
                            },
                            {
                              title: '参数描述',
                              dataIndex: 'enumDesc',
                              showSorterTooltip: false,
                              onCell: (record: any) => ({
                                filed: 'enumDesc',
                                record,
                              }),
                            },
                          ]}
                        />
                      </span>
                    );
                    break;
                }
                return dom;
              },
            },
            {
              title: '读写类型',
              width: 120,
              textWrap: 'word-break',
              ellipsis: true,
              align: 'left',
              dataIndex: 'readWriteType',
              render: (_, record: any) => {
                enum TYPE {
                  读 = 1,
                  读写 = 2,
                }
                return TYPE[record.attributeValue.readWriteType];
              },
            },
            {
              title: '默认值',
              width: 120,
              textWrap: 'word-break',
              ellipsis: true,
              align: 'left',
              dataIndex: 'defaultValue',
            },
            viewmode !== 'view' && {
              title: '操作',
              width: 240,
              render: (_, record, index) => (
                <Space size="middle">
                  <Button
                    type="link"
                    block
                    onClick={() => {
                      setEditData({ ..._, ..._.attributeValue });
                      setCurState([true, 'edit']);
                    }}
                  >
                    编辑
                  </Button>
                  <Button
                    type="link"
                    block
                    onClick={() => {
                      let data = tableData.data;
                      data.splice(index, 1);
                      setTableData({
                        data: data as ColumnsType<DataType>,
                        page: { total: data.length, pageSize: 20, current: 1 },
                      });
                      setReload(reload + 1);
                      onChange && onChange(data);
                      message.info('删除动态属性成功');
                    }}
                  >
                    删除
                  </Button>
                </Space>
              ),
            },
          ] as ColumnsType<DataType>,
          data: tableData,
          attrs: {
            y: 200,
          },
        }}
      />
      {viewmode !== 'view' && (
        <Modal.Dialog
          title={viewmode === 'add' ? '添加动态属性' : '编辑动态属性'}
          showDialog={curState[0]}
          changeDialog={(val: boolean) => setCurState([val, viewmode === 'add' ? 'add' : 'edit'])}
          size={'middle'}
        >
          <DynamicContent
            onFinish={(val: any) => {
              switch (val.type) {
                case 1:
                  val.attributeValue = {
                    unitId: val.unitId,
                    max: val.max,
                    min: val.min,
                    walkLength: val.walkLength,
                    readWriteType: val.readWriteType,
                    type: val.type,
                  };
                  break;
                case 2:
                  val.attributeValue = {
                    stringResult: val.stringResult,
                    readWriteType: val.readWriteType,
                    type: val.type,
                  };
                  break;
                case 3:
                  val.attributeValue = {
                    booleanEnums: val.booleanEnums,
                    readWriteType: val.readWriteType,
                    type: val.type,
                  };
                  break;
                case 4:
                  val.attributeValue = {
                    enums: val.enums,
                    readWriteType: val.readWriteType,
                    type: val.type,
                  };
                  break;
              }
              val.valueJson = JSON.stringify(val.attributeValue);
              let data: any = tableData.data;
              if (viewmode === 'add') {
                data = [...tableData.data, val];
              } else {
                let index = data.findIndex((item: any) => item.id === val.id);
                data.splice(index, 1, val);
              }
              onChange && onChange(data);
              setTableData({
                data: [...data] as ColumnsType<DataType>,
                page: { total: data.length, pageSize: 20, current: 1 },
              });
              setReload(reload + 1);
              setCurState([false, '']);
            }}
            data={editData}
          />
        </Modal.Dialog>
      )}
    </div>
  );
};

export default App;
